import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:xiandou/Request/DioManager.dart';
import 'package:xiandou/Request/NWApi.dart';
import 'package:xiandou/Request/NWMethod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import '../Common.dart';

class RankingScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => RankingScreenState();
}

class RankingScreenState extends State<RankingScreen> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  EasyRefreshController _controller = EasyRefreshController();
  List rankingList = [{'name':'全部','type':'all'},{'name':'日榜','type':'day'},{'name':'月榜','type':'month'}];
  int _selectCategoryIndex = 1;
  int _page = 1;
  List rankingData = [];
  @override
  void initState() {
    super.initState();
    print(rankingList[0].toString());
    requestRankingListData(rankingList[0]['type']);
  }

  void _refresh () {
    _page =1;
    requestRankingListData(rankingList[_selectCategoryIndex]['type']);
  }

  void requestRankingListData(String rankingType) {
    var dic = {'rankingType': rankingType,'page':_page.toString()};
    DioManager().request(
        NWMethod.GET, NWApi.getRankingListlApi, params: dic, success: (data) {
      print(data);
      setState(() {
        rankingData = data;
        _controller.finishLoad(success: true);
        _controller.finishRefresh(success: true,noMore: false);
      });
    }, error: (error) {
      Fluttertoast.showToast(msg: error.message);
    });
  }


  Widget build(BuildContext context) {
    Widget categotyWidget(String label, int index) {
      return new GestureDetector(
          onTap: () {
            _selectCategoryIndex = index;
            setState(() {
              requestRankingListData(rankingList[index]['type']);
            });
          },
          child: Container(
            width: MediaQuery.of(context).size.width / 3,
            child: Column(
              children: <Widget>[
                Expanded(
                    child: Padding(
                      padding: const EdgeInsets.only(top: 8),
                      child: Text(label, style: TextStyle(
                          fontSize: 14, color: Color(0xff333333))),
                    )
                ),
                Offstage(
                    offstage: _selectCategoryIndex == index ? false : true,
                    child: Container(
                      height: 2,
                      width: 27.5,
                      margin: const EdgeInsets.only(bottom: 8),
                      decoration: new BoxDecoration(
                        color: Color(0xffFF5236),
                      ),
                    )
                )
              ],
            ),
          )
      );
    }

    return Scaffold(
      appBar: CupertinoNavigationBar(
        backgroundColor: Colors.white,
        middle: const Text('排行榜'),
        transitionBetweenRoutes:false,
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Container(
              height: 44,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: rankingList.length,
                itemBuilder:(BuildContext context, int index) =>categotyWidget(rankingList[index]['name'], index),
              ),
            ),
            Expanded(
              child: Container(
                child: EasyRefresh(
                  child:ListView.builder(itemBuilder: (BuildContext context,int index){
                    if(rankingData.length == 0) {
                      return Container(
                        padding: const EdgeInsets.only(top: 50),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image(image: AssetImage('assets/d_empty.png'),width: 200,height: 200,),
                            SizedBox(height: 30,),
                            Text('暂无内容',style: TextStyle(color: Common.darkColor,fontSize: 14),),
                          ],
                        ),
                      );
                    }
                    String url =rankingData[index]['avatar'];
                    return Container(
                      margin: const EdgeInsets.fromLTRB(15, 4, 15, 4),
                      height: 54,
                      color: Color(0xffF7EBEA),
                      child: Row(
                        children: <Widget>[
                          Container(
                            margin: const EdgeInsets.only(left: 36),
                            child: Image.asset('assets/gold.png',width: 24,height:27,),
                          ),
                          Expanded(
                              child:Container(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    ClipOval(
                                      child: Image.network(
                                        url != null ? url : 'https://pic2.zhimg.com/v2-639b49f2f6578eabddc458b84eb3c6a1.jpg',
                                        width: 30,
                                        height: 30,
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                    SizedBox(width: 10,),
                                    Text(rankingData[index]['nickname'])
                                  ],
                                ),
                              )
                          ),
                          Container(
                            width: 70,
                            margin: const EdgeInsets.only(right: 15),
                            child: Text(rankingData[index]['totalAmount'].toString(),style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),textAlign: TextAlign.end,),
                          )
                        ],
                      ),
                    );
                  }, itemCount: rankingData.length == 0 ? 1 : rankingData.length,),
                  onRefresh: () async{
                    _refresh();
                  },
                  onLoad: () async{
//                    _onLoadmore();
                  },
//                  enableControlFinishLoad: true,
//                  enableControlFinishRefresh: true,
                )
              ),
            ),
            Container(
              color: Color(0xffDE1F00),
              height: 50,
              alignment: Alignment.center,
              margin: const EdgeInsets.only(bottom: 0),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    ClipOval(
                      child: Image.network(
                        'https://pic2.zhimg.com/v2-639b49f2f6578eabddc458b84eb3c6a1.jpg',
                        width: 30,
                        height: 30,
                        fit: BoxFit.cover,
                      ),
                    ),
                    SizedBox(width: 8,),
                    Text.rich(
                        TextSpan(
                            children: [
                              TextSpan(text: '我当前排名',style: TextStyle(color: Colors.white,fontSize: 15)),
                              TextSpan(text: '第20名',style: TextStyle(color: Colors.orangeAccent,fontSize:17 )),
                            ]
                        )
                    )
                  ],
                ),
            )
          ],
        ),
      ),
    );
  }
}